
<template>
  <div class="allocMenu">
    <el-dialog title="分配菜单" :visible.sync="allocMenuVisible" 
      width="75%"
    >
      <el-tree
        class="allocTree"
        :data="menuTreeList"
        show-checkbox
        node-key="menuId"
        :props="defaultProps"
        ref="tree"

      >
      </el-tree>
      <div class="allocMenu_buttom">
        <el-row>
          <el-button @click="handleClear()">重置</el-button>
          <el-button type="primary" @click="handleSave()">保存</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import role from "@/api/role";
export default {
  data() {
    return {
      menuTreeList: [],
      defaultProps: {
        children: "children",
        label: "title",
      },
      allocMenuVisible: false,
      roleId: 0,
    };
  },
  created() {
    this.treeList();
  },
  methods: {
    treeList() {
      role.treeMenuList().then((res) => {
        this.menuTreeList = res.data;
      });
    },

    singAllocMenu(roleId){
      this.roleId = roleId
      this.getRoleMenu(this.roleId)
      this.allocMenuVisible = true
    },

    /**
     * @param roleId 角色的ID,由父组件传递过来
     */
    getRoleMenu(roleId) {
      role.listMenu(roleId).then((res) => {
        //获取数据,该角色已经有过的权限
        let menuList = res.data;
        //用来存储角色有的菜单, 并勾选
        let checkedMenuIds = [];
        if (menuList != null && menuList.length > 0) {
          menuList.forEach((menu) => {
            //只添加子菜单, 父菜单也会显示勾选
            //所以父菜单不需要添加, 等保存在获取就好
            if (menu.parentId !== 0) {
              checkedMenuIds.push(menu.menuId);
            }
          });
        }
        //调用这个ui组件自带的方法
        this.$refs.tree.setCheckedKeys(checkedMenuIds);
      });
    },
    //分配菜单
    handleSave() {
      //获取勾选到的菜单
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      let checkedMenuIds = new Set();
      if (checkedNodes != null && checkedNodes.length > 0) {
        checkedNodes.forEach((checkedNode) => {
          //存储选中菜单的ID
          checkedMenuIds.add(checkedNode.menuId)
          if(checkedNode.parentId !== 0){
              checkedMenuIds.add(checkedNode.parentId)
          }
        });
      }
      this.$confirm('是否分配菜单?','提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning'
      }).then(()=>{
        let params = new URLSearchParams();
        params.append("roleId",this.roleId);
        params.append("menuIds",Array.from(checkedMenuIds));
        role.allocMenu(params).then(res=>{
          this.$message({
            message:'分配成功',
            type:'success',
            duration:1000
          })
          this.allocMenuVisible = false
          this.$router.back();
        })
      })
    },
    handleClear() {
        this.getRoleMenu(this.roleId)
    }
  },
};
</script>

<style lang="scss" scoped>
.allocTree {
  padding: 0px 10px 0px 10px;
}
.allocMenu_buttom {
  margin-top: 50px;
  text-align: center;
}
</style>